package com.heimatest.random_named;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;

public class MyJFrame extends JFrame {
    JPanel center;

    public MyJFrame() {
        init();
        initCenter();
        initSouth();
        this.setVisible(true);
    }

    public void init() {
        this.setTitle("Random Named Example");
        this.setSize(600, 400);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setLayout(new BorderLayout());
    }

    private void initCenter() {
        center = new JPanel();
        center.setLayout(new FlowLayout(FlowLayout.LEFT));
        for (int i = 0; i < 30; i++) {
            JButton jbb = new JButton("张三" + i);
            jbb.setBackground(new Color(255, 255, 255));
            center.add(jbb);
        }
        this.add(center, BorderLayout.CENTER);
    }

    private void initSouth() {

        JPanel south = new JPanel();
        JButton jb = new JButton("点名");
        south.add(jb);
        Random ra = new Random();
        this.add(south, BorderLayout.SOUTH);
        jb.addMouseListener(new MouseAdapter() {
            Component comp = null;

            public void mouseClicked(MouseEvent e) {
                if (comp != null) {
                    comp.setBackground(Color.WHITE);
                }
                Component[] components = center.getComponents();
                int n = ra.nextInt(components.length);
                components[n].setBackground(Color.red);
                comp = components[n];
            }
        });

    }
}
